<?php

namespace app\com\simtoon\utils;
use app\com\simtoon\base\BaseCommand;
use yii\base\Exception;
use app\com\simtoon\log\LogUtils;
/**
 * User用户辅助类
 */
class UserUtils extends BaseCommand{


//    /**
//     * 2015-11-05 add by hetao
//     * 注册用户的同时送红包
//     * @param array $user
//     * @return 用户ID(uid)
//     */
//    public function regist_user($model, array $user_attr, $isTransaction = true)
//    {
//        /*
//         * 1.查询红包类型为注册送红包
//         * 2.有红包，注册用户，送红包
//         * 3.没有红包，只注册用户
//         */
//        if($isTransaction){
//            $transaction = $this->connection->beginTransaction();
//            try{
//                //注册用户
//                $succ = $this->save_user($model,$user_attr);
//                if(!$succ){ //保存失败
//                    $transaction->rollBack();
//                    return -1;
//                }
//                $uid = $model->getAttribute('uid');
//                $res = $this->save_user_bonus($uid);
//                if($res < 0){
//                    $transaction->rollBack();
//                    return -1;
//                }
//                $transaction->commit();
//                return $uid;
//            }catch (Exception $e){
//                LogUtils::error($e->getMessage(), __METHOD__);
//                $transaction->rollBack();
//                return -1;
//            }
//        }else{
//            $succ = $this->save_user($model,$user_attr);
//            if(!$succ){ //保存失败
//                return -1;
//            }
//            $uid = $model->getAttribute('uid');
//            $res = $this->save_user_bonus($uid);
//            if($res < 0){
//                return -1;
//            }
//            return $uid;
//        }
//
//    }


//    /**
//     * 2015-11-30 update by hetao  没有事务
//     * 添加用户的同时送红包，
//     * @param array $user
//     * @return 用户ID(uid)
//     */
//    public function regist_user($uid, array $user_attr)
//    {
//        /*
//         * 1.查询红包类型为注册送红包
//         * 2.有红包，注册用户，送红包
//         * 3.没有红包，只注册用户
//         */
//        try{
//            //注册用户
//            $res = $this->getCommand()->insert('supe_user', $user_attr)->execute();
//            if($res < 0){ //保存失败
//                return -1;
//            }
//            $res = $this->save_user_bonus($uid);
//            if($res < 0){
//                return -1;
//            }
//            return $uid;
//        }catch (Exception $e){
//            LogUtils::error($e->getMessage(), __METHOD__);
//            return -1;
//        }
//
//    }

    /**
     * 2016-5-9 新方法
     * @param array $user
     * @return 用户ID(uid)
     */
    public function regist_user(array $user_attr)
    {
        try{
            //注册用户
            $res = $this->getCommand()->insert('supe_user', $user_attr)->execute();
            if($res < 0){ //保存失败
                return -1;
            }
            return $res;
        }catch (Exception $e){
            LogUtils::error($e->getMessage(), __METHOD__);
            return -1;
        }

    }
   //2016 05 23 更新手机注册用户的信息，
    public function update_phone__user($id,$nickname,$openid,$headimgurl)
    {
        try{

            $res = $this->execUpdate('supe_user', ['nickname' =>$nickname,'headimgurl'=>$headimgurl,'openid'=>$openid
            ],'uid ='.$id);

            return $res;
        }catch (Exception $e){
            LogUtils::error($e->getMessage(), __METHOD__);
            return -1;
        }

    }




   //更新用户表 头像 昵称 字段
    public function update_user($id,$nickname,$headimgurl)
    {
        try{


            $res = $this->execUpdate('supe_user', ['nickname' =>$nickname,'headimgurl'=>$headimgurl
            ],'uid ='.$id);

            return $res;
        }catch (Exception $e){
            LogUtils::error($e->getMessage(), __METHOD__);
            return -1;
        }

    }



    /**
     * 2015-11-20 add by hetao: 保存用户
     * @param $model  User类对象
     * @param array $user_attr  用户信息
     * @return mixed
     */
    public function save_user(&$model, array $user_attr){
        $model->setIsNewRecord(true);
        $model->setAttributes($user_attr,false);
        return $model->save();
    }

    /**
     * 2015-11-20 add by hetao: 保存用户红包
     * @param $uid  用户ID
     * @param $bonus_res  红包
     */
    public function save_user_bonus($uid){
        $res = -1;
        $date = date('Y-m-d');
        //查询红包
        $sql = "SELECT bonus_type_id FROM fang_bonus_type WHERE bonus_send_type = 1
                    AND send_start_date <= '".$date."' AND send_end_date >= '".$date."'";
        $bonus_res = $this->queryColumn($sql);
        //注册成功，有红包类型
        if(count($bonus_res) <= 0){
            return 1;
        }
        foreach($bonus_res as $key=>$val){
            if($val === '3'){
                $res = $this->getCommand()->insert('supe_user_bonus', [
                    'bonus_type_id'=>$val,
                    'bonus_sn'=>'美家邦图',
                    'uid'=>$uid,
                    'bonus_status'=>0
                ])->execute();
            }else{
                $bonus_sn = $this->generate_code($uid);
                $res = $this->getCommand()->insert('supe_user_bonus', [
                    'bonus_type_id'=>$val,
                    'bonus_sn'=>$bonus_sn,
                    'uid'=>$uid,
                    'bonus_status'=>0
                ])->execute();
            }
        }
        return $res;
    }

    /**
     * 2015-11-06 add by hetao: 生成随机码
     * @param $uid  用户ID
     * @param int $code_length  随机码长度
     */
    public function generate_code($uid,$code_length = 12)
    {
        //获得UUID
        $uuid = Uuid::createV4();
        $uuid_str = $uuid->getField('time_low').
            $uuid->getField('time_mid').
            $uuid->getField('time_hi_version').
            $uuid->getField('clock_seq_hi_variant').
            $uuid->getField('clock_seq_low').
            $uuid->getField('node');
        //提取UUID中的数字，和随机数拼接
        $res = mt_rand() . preg_replace('/\D/s', '', $uuid_str);
        $len = strlen($uid);//取uid长度
        $res = $uid . substr($res,0,$code_length - $len);//将uid和截取的UUID拼接
        //查询红包编号是否存在
        if($this->get_bonus_by_sn($res)){
            $this->generate_code($uid, $code_length);
        }
        return $res;
    }

    /**
     * 2015-11-06 add by hetao
     * 根据红包编号，查询是否已经存在
     * @param $bonus_sn
     * @return boolean 存在true，否则false
     */
    public function get_bonus_by_sn($bonus_sn)
    {
        $sql = "SELECT bonus_id FROM supe_user_bonus WHERE bonus_sn = ".$bonus_sn;
        $res = $this->queryColumn($sql);
        if(count($res) > 0){
            return true;
        }
        return false;

    }

    /**
     * 2015-11-06 add by hetao
     * 根据用户UID查询在发送有效期内，所有未领用的红包
     * @param $uid  用户UID
     * @param $status 领用状态，默认未领用
     * @param bool $is_validate_date 是否验证发送有效期
     * @return array 所有红包
     */
    public function get_bonus_by_uid($uid, $status = 0, $is_validate_date = true)
    {
        $date = date('Y-m-d');
        $sql = " SELECT fang_bonus_type.bonus_type_id,
                        fang_bonus_type.bonus_type_name,
                        fang_bonus_type.bonus_type_money,
                        fang_bonus_type.bonus_send_type,
                        fang_bonus_type.bonus_type,
                         CASE fang_bonus_type.bonus_type
                               WHEN 1 THEN '购房抵价红包'
                               WHEN 2 THEN '租房抵价红包'
                               WHEN 3 THEN '请在Uber APP输入红包编号进行领取（限Uber新用户）'
                          END bonus_name,
                        fang_bonus_type.use_start_date,
                        fang_bonus_type.use_end_date,
                        supe_user_bonus.bonus_id,
                        supe_user_bonus.bonus_sn,
                        supe_user_bonus.bonus_status
                 FROM
                       supe_user_bonus,
                       fang_bonus_type
                 WHERE supe_user_bonus.bonus_type_id = fang_bonus_type.bonus_type_id
                 AND supe_user_bonus.bonus_status = ".$status."
                 AND supe_user_bonus.uid = ".$uid;
        if($is_validate_date)
        {
            $sql .= " AND fang_bonus_type.send_start_date <= '".$date."' AND fang_bonus_type.send_end_date >='".$date."'";
        }
        $res = $this->queryAll($sql);
        return $res;
    }


    /**
     * 2015-11-07 add by hetao
     * 根据用户UID和红包ID领取红包
     * @param $uid
     * @param $bonus_ids
     */
    public function receive_bonus($uid, array $bonus_ids)
    {
        $sql_arr = array();
        $date = date('Y-m-d H:i:s');
        foreach($bonus_ids as $key=>$val){
            $sql = " UPDATE supe_user_bonus set bonus_status = 1, get_date = '".$date.
                   "' WHERE uid = ".$uid." AND bonus_id = ".$val;
            array_push($sql_arr,$sql);
        }
        $res = $this->executeSqlBatch($sql_arr);
        return $res;
    }

	
}

?>